import java.text.DecimalFormat;
import java.util.EmptyStackException;

/**
 * Created by Mose on 2017/10/9.
 */
public class ArrayStack<T> implements Stack<T> {
    private final int DEFAULT_CAPACITY = 10;
    private int count;
    private T[] stack;

    public ArrayStack() {
        count = 0;
        stack = (T[]) (new Object[DEFAULT_CAPACITY]);
    }

    public void push(T element) {
        if (count == stack.length)
            expandCapacity();
        stack[count] = element;
        count++;
    }

    public String toString() {
        String result = "<top of stack>\n";
        for (int index = count - 1; index >= 0; index--)
            result += stack[index] + "\n";
        return result + "<bottom of stack>";
    }

    private void expandCapacity() {
        T[] larger = (T[]) (new Object[stack.length * 2]);
        for (int index = 0; index < stack.length; index++)
            larger[index] = stack[index];
        stack = larger;

    }

    public int size() {
        return count;
    }

    public boolean isEmpty() {
        if (count == 0)
            return true;
        else
            return false;
    }

    public T peek() throws EmptyStackException {
        if (count==0)
            System.out.println("Error.");
        return stack[count - 1];
    }

    public T pop() throws EmptyStackException {
        if (count==0)
            System.out.println("Error.");
        T result = stack[count-1];
        count = count-1; //count--
        stack[count]=null;
        return result;
    }
}
